package org.mf.dao.jpa;

import javax.persistence.Query;

import org.mf.common.utils.RandomStringGenerator;
import org.mf.dao.UserDAO;
import org.mf.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("userDao")
@Transactional
public class UserDaoJpa extends GenericDaoJpa<User> implements UserDAO {
	private RandomStringGenerator randomStringGenerator;
	private Md5PasswordEncoder passwordEncoder;

	public UserDaoJpa() {
		super(User.class);
	}

	public RandomStringGenerator getRandomStringGenerator() {
		return randomStringGenerator;
	}

	@Autowired
	public void setRandomStringGenerator(
			RandomStringGenerator randomStringGenerator) {
		this.randomStringGenerator = randomStringGenerator;
	}

	public Md5PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	@Autowired
	public void setPasswordEncoder(Md5PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public User getUserByUsername(String username) {
		Query q = getEntityManager().createNamedQuery("findUserByUsername");
		q.setParameter("username", username);
		return (User) q.getSingleResult();
	}

	@Override
	public void save(User user) {
		// set the encripted password and salt
		user.setSalt(randomStringGenerator.getRandomSalt());
		user.setPassword(passwordEncoder.encodePassword(user.getPassword(),
				user.getSalt()));
		super.save(user);
	}

}
